<template>
  <div :class="treeStore.isShowStrategyDetail ? 'not-click' : ''">
    <!-- <h1 class="title">日志设置</h1> -->
    <div v-loading="loading">
      <div class="setting-box logSetCon outreach-box">
        <div class="titleMargin">
          <div class="leftCont">安全防护事件审计策略</div>
          <div>
            <el-radio v-model="data.radio2" @change="changeReport" value="0"
              >审计操作系统所有对象运行事件</el-radio
            >
          </div>
        </div>
        <div class="lineMargin" v-if="getType()">
          <div class="leftCont"></div>
          <div>
            <el-radio v-model="data.radio2" @change="changeReport" value="1"
              >仅审计当前部署策略名单内的对象运行事件</el-radio
            >
          </div>
        </div>
        <div class="lineMargin">
          <div class="leftCont"></div>
          <div>
            <el-radio v-model="data.radio2" @change="changeReport" value="2"
              >仅审计当前部署策略名单外的对象运行事件</el-radio
            >
          </div>
        </div>
        <div class="logSet" v-if="treeStore.osType == 'win'">
          <div class="sendSet">
            <div class="text">事件日志上报设置</div>
            <div>
              <div class="item">
                <div>
                  <el-switch
                    v-model="data.logSet.PROCESS.normal"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeEvent"
                  >
                  </el-switch>
                  <span class="tip"> 应用程序管控日志 </span>
                </div>

                <div class="subItem" v-if="data.logSet.PROCESS.normal === 1">
                  <el-switch
                    v-model="data.logSet.PROCESS.reportAll"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeEvent"
                  >
                  </el-switch>
                  <span class="tip"> 审计模式上传应用日志 </span>
                </div>
              </div>

              <div class="item">
                <div>
                  <el-switch
                    v-model="data.logSet.REINFORCEMENT.normal"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeEvent"
                  >
                  </el-switch>
                  <span class="tip"> 外设管控设置 </span>
                </div>

                <div
                  class="subItem subItem2"
                  v-if="data.logSet.REINFORCEMENT.normal === 1"
                >
                  <el-switch
                    v-model="data.logSet.REINFORCEMENT.reportAll"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeEvent"
                  >
                  </el-switch>
                  <span class="tip"> 审计模式上传外设日志 </span>
                </div>
              </div>
              <div class="item">
                <div>
                  <el-switch
                    v-model="data.logSet.NETWORK.normal"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeEvent"
                  >
                  </el-switch>
                  <span class="tip"> 非法外联管控日志 </span>
                </div>
              </div>
              <!-- <div class="item">
                <div>
                  <el-switch
                    v-model="data.logSet.PLATFORM.normal"
                    :active-value="1"
                    :inactive-value="0"
                    @change="changeEvent"
                  >
                  </el-switch>
                  <span class="tip"> 卫士运行日志 </span>
                </div>
              </div> -->
            </div>
          </div>
        </div>
      </div>

      <HETTable1
        ref="logServerTable"
        :tableData="data.tableData"
        :tHead="data.tHead"
        :headerOperation="headerOperation"
        :total="data.total"
        @getTableData="getLogSetInfo"
      >
        <template #enable>
          <el-table-column slot="enable" label="启用" :width="251">
            <template #default="scope">
              <el-switch
                v-model="scope.row.enabled"
                :disabled="data.switchDisabled"
                @change="changeEnabled(scope.row.server, scope.row.enabled)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </template>

        <template #operation>
          <el-table-column slot="operation" label="操作">
            <template #default="scope">
              <span class="mr-6">
                <el-text type="primary" class="cursor-pointer" @click="edit(scope.row, scope.$index)">修改</el-text>
              </span>
              <el-text type="primary" class="cursor-pointer" @click="deleteServerTip(scope.row)">删除</el-text>
            </template>
          </el-table-column>
        </template>
      </HETTable1>
    </div>
    <el-dialog
      :model-value="data.dialogAsync"
      :title="data.dialogTitle"
      :center="true"
      width="30%"
      :close-on-click-modal="false"
      @close="closeDialog(logForm)"
    >
      <div class="config-body">
        <el-form ref="logForm" :model="data.form" :rules="data.rules" label-width="150px">
          <el-form-item label="日志服务器地址" prop="server">
            <el-input v-model="data.form.server" placeholder="请填写日志服务器IP地址">
            </el-input>
          </el-form-item>
          <el-form-item label="端口号" prop="port">
            <el-input
              v-model.number="data.form.port"
              placeholder="请填写日志服务器端口号，默认是514"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="启用" prop="enabled">
            <el-switch
              v-model="data.form.enabled"
              :active-value="true"
              :inactive-value="false"
            >
            </el-switch>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(logForm)">确定</el-button>
          <el-button @click="closeDialog(logForm)">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, markRaw } from "vue";
import { Search, Refresh, Delete, Plus } from "@element-plus/icons-vue";
import { req_getLogSetInfo, req_setLogSetInfo } from "~/utils/axios/index.js";
import { validIp, validPort } from "~/utils/common/validation.js";
import { useTreeStore } from "~/utils/pinia/tree.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { eventBus } from "~/utils/common/eventBus.js";
import ProgramWhitelist from "~/components/StrategyManagement/ProgramWhitelist/components/ProgramWhitelist.vue";
import WhitelistWindows from "~/components/StrategyManagement/ProgramWhitelist/components/WhitelistWindows.vue";
import BuiltInWhitelist from "~/components/StrategyManagement/ProgramWhitelist/components/BuiltInWhitelist.vue";
import ExceptionProgram from "~/components/StrategyManagement/ProgramWhitelist/components/ExceptionProgram.vue";
import ProtectionSettings from "~/components/StrategyManagement/ProgramWhitelist/components/ProtectionSettings.vue";
import KillSettings from "~/components/StrategyManagement/ProgramWhitelist/components/KillSettings.vue";
eventBus.on("getStrategyDetail", (detail) => {
  treeStore.openTreeFlag = false;
  if (treeStore.osType == "win") {
    data.logSet = JSON.parse(detail.data[1].report_mode);
    data.tableData = JSON.parse(detail.data[2].syslog_server);
  } else {
    data.tableData = JSON.parse(detail.data[1].syslog_server);
  }
  data.radio2 = detail.data[0].audit_policy;
  data.total = data.tableData.length;
});

const treeStore = useTreeStore();
treeStore.openTree();
const logForm = ref();
const logServerTable = ref();
treeStore.treeLinkedTableRef = logServerTable;
const loading = ref(false);
onMounted(() => {
  // getLogSetInfo()
});

const getType = () => {
  if (treeStore.osType == 'win') {
    return true;
  } else {
    return false;
  }
}

const data = reactive({
  dialogTitle: "新建服务器地址",
  switchDisabled: false,
  dialogAsync: false,
  radio2: "",
  logSet: {
    PROCESS: {
      normal: 1,
      reportAll: 0,
    },
    REINFORCEMENT: {
      normal: 1,
      reportAll: 0,
    },
    NETWORK: {
      normal: 1,
    },
    PLATFORM: {
      normal: 1,
    },
  },
  tHead: [
    {
      label: "日志服务器地址",
      prop: "server",
      isCustom: false,
      // width: 300,
    },
    {
      label: "端口号",
      prop: "port",
      isCustom: false,
      // width: 251,
    },
    {
      label: "启用",
      prop: "enabled",
      isCustom: true,
      slotName: "enable",
    },
    {
      label: "操作",
      isCustom: true,
      slotName: "operation",
    },
  ],

  tableData: [],
  total: null,
  form: {
    server: "",
    port: 514,
    enabled: false,
  },
  rules: {
    server: [
      { required: true, message: "服务器IP地址不能为空", trigger: "blur" },
      { validator: validIp, trigger: "blur" },
    ],
    port: [
      { required: true, message: "端口号不能为空", trigger: "blur" },
      { validator: validPort, trigger: "blur" },
    ],
  },
});
const addLogServer = () => {
  editIdx.value = null;
  data.dialogAsync = true;
  data.dialogTitle = "新建服务器地址";
  data.from = {
    server: "",
    port: 514,
    enabled: false,
  };
};
const headerOperation = ref([
  {
    name: "新建地址",
    icon: markRaw(Plus),
    tip: "注:最多支持向3个日志服务器发送日志",
    inLeft: true,
    disabled: false,
    handleClick: addLogServer,
  },
]);
const editIdx = ref(null);
const edit = (row, index) => {
  editIdx.value = index;
  data.dialogAsync = true;
  data.dialogTitle = "编辑服务器地址";
  data.form = row;
};
const deleteServerTip = (row) => {
  ElMessageBox.confirm("确定要删除该日志服务器？", "删除日志服务器", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    center: true,
    closeOnClickModal: false,
  }).then(() => {
    data.tableData = data.tableData.filter((item) => {
      return item != row;
    });
    let params = [
      {
        key: "syslog_server",
        value: JSON.stringify(data.tableData),
      },
    ];
    setLogSetInfo(params);
  });
};
const changeReport = () => {
  let params = [
    {
      key: "audit_policy",
      value: data.radio2,
    },
  ];
  setLogSetInfo(params);
};
const changeEvent = () => {
  let params = [
    {
      key: "report_mode",
      value: JSON.stringify(data.logSet),
    },
  ];
  setLogSetInfo(params);
};
const changeEnabled = () => {
  let params = [
    {
      key: "syslog_server",
      value: JSON.stringify(data.tableData),
    },
  ];
  setLogSetInfo(params);
};
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (data.dialogTitle === "编辑服务器地址") {
        data.tableData[editIdx.value] = data.form;
      } else {
        if (data.total >= 3) {
          ElMessage.error("最多支持向3个日志服务器发送日志");
          return false;
        }
        data.tableData.push(data.form);
      }
      let params = [
        {
          key: "syslog_server",
          value: JSON.stringify(data.tableData),
        },
      ];
      setLogSetInfo(params);
      data.dialogAsync = false;
    } else {
      return false;
    }
  });
};
const closeDialog = (formEl) => {
  if (!formEl) return;
  data.dialogAsync = false;
  getLogSetInfo();
};
const getLogSetInfo = async () => {
  if (!treeStore.treeDeviceId) return;
  loading.value = true;
  let params = ["audit_policy", "syslog_server", "report_mode"];
  try {
    const { data: res } = await req_getLogSetInfo(treeStore.treeDeviceId, params);
    loading.value = false;
    if (res.status) {
      data.radio2 = res.data[0].audit_policy;
      if (treeStore.osType == "win") {
        data.logSet = JSON.parse(res.data[1].report_mode);
        data.tableData = JSON.parse(res.data[2].syslog_server);
      } else {
        data.tableData = JSON.parse(res.data[1].syslog_server);
      }
      data.total = data.tableData.length;
      headerOperation.value[0].disabled = data.total >= 3;
    }
  } catch (err) {
    loading.value = false;
  }
};
const setLogSetInfo = (params) => {
  if (!treeStore.treeDeviceId) return;
  req_setLogSetInfo(treeStore.treeDeviceId, params).then((res) => {
    if(res.data.succeed) {
      ElMessage.success("操作成功");
    }
    getLogSetInfo();
  });
};
</script>

<style lang="scss" scoped>
.logSetCon {
  background: #fff;
  padding: 10px 20px;
  margin-bottom: 15px;
}
.titleMargin {
  display: flex;
  align-items: center;
}
.leftCont {
  width: 160px;
  margin-right: 15px;
  font-size: 16px;
  text-align: right;
}
.lineMargin {
  display: flex;
  margin-top: 20px;
}
.logSet {
  margin-bottom: 10px;
  .sendSet {
    display: flex;
    margin-top: 15px;
    .text {
      width: 160px;
      margin-right: 15px;
      font-size: 14px;
      text-align: right;
    }
    .item {
      margin-bottom: 5px;
      display: flex;
      align-items: center;
      .tip {
        margin-left: 5px;
        font-size: 14px;
        color: #606266;
      }
      .subItem {
        margin-left: 20px;
      }
      .subItem.subItem2 {
        margin-left: 48px;
      }
    }
  }
}
.func {
  position: absolute;
  top: 345px;
  left: 0;
  display: flex;
  align-items: center;
  .tip {
    line-height: 22px;
    color: #c2c2c2;
    font-size: 12px;
    margin-left: 10px;
  }
}
.config-body{
  padding: 0 30px 0 10px;
}
</style>
